from sklearn.mixture import GaussianMixture
import numpy as np
from scipy.stats import norm
from sklearn.cluster import KMeans
import pandas as pd


# -----------------------------------------------------------------------------------------------------------------------------具体实现对比
# 初始化参数
np.random.seed(0)
K = 3       # 高斯分布数量
N = K*1000    # 数据量
mu_init = np.array([10, 5, 8])  # 模拟数据均值
sigma_init = np.array([1, 1, 1])  # 模拟数据方差
pi_init = np.array([1/K]*K)  # 初始混合系数

data = np.concatenate([np.random.normal(mu_init[i], sigma_init[i], N//K) for i in range(K)])        # 生成模拟数据
# -----------------------------------------------------------------------------------------------------------------------------首先看封装的结果
gm = GaussianMixture(n_components=3)
gm.fit(data.reshape(-1, 1))
print("EM - GaussianMixture Means:", gm.means_.flatten())
















# -----------------------------------------------------------------------------------------------------------------------------具体实现



import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 生成三维模拟数据
N = 1000
mean1 = [1, 2, 3]
cov1 = [[1, 0.1, 0.2], [0.1, 1, 0.3], [0.2, 0.3, 1]]
data1 = np.random.multivariate_normal(mean1, cov1, N)

mean2 = [5, 6, 7]
cov2 = [[1, -0.2, 0], [-0.2, 1, -0.5], [0, -0.5, 1]]
data2 = np.random.multivariate_normal(mean2, cov2, N)

data = np.vstack([data1, data2])
true_labels = np.array([0]*N + [1]*N)

# K-means
kmeans = KMeans(n_clusters=2)
kmeans_labels = kmeans.fit_predict(data)
kmeans_colors = np.where(kmeans_labels == true_labels, kmeans_labels, -1)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=kmeans_colors)
ax.set_title('K-means Clustering')
plt.show()

# EM
gm = GaussianMixture(n_components=2)
gm_labels = gm.fit_predict(data)
gm_colors = np.where(gm_labels == true_labels, gm_labels, -1)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=gm_colors)
ax.set_title('EM Clustering')
plt.show()
